package pers.duorhs.easierfeign.config;

import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.context.annotation.Configuration;
import pers.duorhs.easierfeign.iface.GeneralRemoteClient;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Duorhs
 * @date 2022/1/12 15:26
 */
@Configuration
@ConditionalOnProperty(prefix = "easierfeign", name = "isConsumer", havingValue = "true")
@EnableConfigurationProperties(EasierFeignProperties.class)
public class EasierFeignClientsConfiguration {

    public static ConcurrentHashMap<String, GeneralRemoteClient> clientMap = new ConcurrentHashMap<>();

    @Autowired
    public EasierFeignClientsConfiguration(FeignContext feignContext, List<EasierFeignProperties.ClientProperties> clientProperties) {
        for (EasierFeignProperties.ClientProperties properties : clientProperties) {

            String name = properties.provider;
            String prefix = properties.prefix;

            String url = "http://" + name + "/" + prefix;

            /*builder 相关的对象 finally get it！！*/
            Contract contract = feignContext.getInstance(name, Contract.class);
            Encoder encoder = feignContext.getInstance(name, Encoder.class);
            Decoder decoder = feignContext.getInstance(name, Decoder.class);
            Client client = feignContext.getInstance(name, Client.class);
            ErrorDecoder errorDecoder = feignContext.getInstance(name, ErrorDecoder.class);


            GeneralRemoteClient target = Feign.builder()
                    .contract(contract)
                    .encoder(encoder)
                    .decoder(decoder)
                    .client(client)
                    .errorDecoder(errorDecoder)
                    .target(GeneralRemoteClient.class, url);

            clientMap.put(name, target);
        }
    }


}
